package com.youi.third.yibaopay;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yeepay.g3.sdk.yop.client.YopRequest;
import com.yeepay.g3.sdk.yop.client.YopResponse;
import com.yeepay.g3.sdk.yop.client.YopRsaClient;
import com.yeepay.g3.sdk.yop.encrypt.DigitalEnvelopeDTO;
import com.yeepay.g3.sdk.yop.utils.DigitalEnvelopeUtils;
import com.youi.common.Common;
import com.youi.entity.Userorder;
import com.youi.entity.Userwechat;
import com.youi.entity.Yibaodivide;
import com.youi.entity.Yibaopayment;
import com.youi.third.wechat.util.WechatUtil;
import com.youi.third.yibaopay.model.CashierdeskResult;
import com.youi.third.yibaopay.model.DivideBackDetail;
import com.youi.third.yibaopay.model.Divideresult;
import com.youi.third.yibaopay.model.Refundresult;
import com.youi.third.yibaopay.model.YibaoorderResult;
import com.youi.util.JsonUtil;
import com.youi.util.SmsUtil;
import sun.misc.BASE64Decoder;

import java.io.IOException;
import java.io.InputStream;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * 易宝支付工具类
 *
 * @author Administrator
 */
public class YibaopayUtil {

    public static String PRIVATEKEY = null;//平台商密钥
    public static String ParentMerchantNo = null;//系统商编
    public static String MerchantNo = null;//子商户编号
    public static String NotifyUrl = null;//支付成功服务器回调地址
    public static String RefundNotifyUrl = null;//退款成功服务器回调地址
    public static String PUBLICKEY = null;//平台商公钥

    /**
     * 加载配置文件
     */
    static {
        Properties prop = new Properties();
        InputStream in = YibaopayUtil.class.getResourceAsStream("/yibaopay.properties");
        try {
            prop.load(in);
            String prefix = "yibaopay.";//前缀
            PRIVATEKEY = prop.getProperty(prefix + "PRIVATEKEY").trim();
            ParentMerchantNo = prop.getProperty(prefix + "ParentMerchantNo").trim();
            MerchantNo = prop.getProperty(prefix + "MerchantNo").trim();
            NotifyUrl = prop.getProperty(prefix + "NotifyUrl");
            RefundNotifyUrl = prop.getProperty(prefix + "RefundNotifyUrl".trim());
            PUBLICKEY = prop.getProperty(prefix + "PUBLICKEY".trim());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private YibaopayUtil() {

    }

    /**
     * 创建易宝订单
     * 返回token
     *
     * @param serialNumber 订单流水号(主订单号)
     * @param amount       订单金额
     * @return
     * @throws IOException
     */
    public static YibaoorderResult createOrder(String serialNumber, Double amount) throws IOException {
        Map<String, String> parms = new HashMap<>();
        YopRequest request = new YopRequest("OPR:" + ParentMerchantNo, PRIVATEKEY);
        parms.put("parentMerchantNo", ParentMerchantNo);
        parms.put("merchantNo", MerchantNo);
        //订单号
        parms.put("orderId", serialNumber);
        //订单金额(单位:元)
        DecimalFormat orderAmount = new DecimalFormat("0.00");
        parms.put("orderAmount", orderAmount.format(amount));
        //服务器通知地址
        parms.put("notifyUrl", NotifyUrl);

        request.addParam("parentMerchantNo", ParentMerchantNo);
        request.addParam("merchantNo", MerchantNo);
        request.addParam("orderId", serialNumber);
        request.addParam("orderAmount", orderAmount.format(amount));
        request.addParam("notifyUrl", NotifyUrl);
        request.addParam("goodsParamExt", "{\"goodsName\":\"美宜佳健康商城商品\",\"goodsDes\":\"美宜佳健康商城商品\"}");
        request.addParam("fundProcessType", "DELAY_SETTLE");
        //签名
        request.addParam("hmac", HmacUtil.gethamc(parms));
        // 发送请求
        YopResponse response = YopRsaClient.post("/rest/v1.0/sys/trade/order", request);
        //解析返回
        YibaoorderResult createOrderResult = null;
        if ("FAILURE".equals(response.getState())) {
            if (response.getError() != null) {
                createOrderResult.setCode(response.getError().getCode());
                createOrderResult.setMessage(response.getError().getMessage());
            }
        }
        if (response.getStringResult() != null) {
            String jsonString = JsonUtil.toJson(response.getResult());
            createOrderResult = JsonUtil.fromJson(jsonString, YibaoorderResult.class);
        }
        return createOrderResult;
    }


    /**
     * 查询易宝订单
     *
     * @param orderNo       订单流水号(主订单号)
     * @param uniqueOrderNo 易宝订单流水号
     * @throws IOException
     */
    public static JSONObject getYibaoorder(String orderNo, String uniqueOrderNo) throws IOException {
        //签名参数
        Map<String, String> param = new HashMap<>();
        param.put("parentMerchantNo", ParentMerchantNo);
        param.put("merchantNo", MerchantNo);
        param.put("orderId", orderNo);
        param.put("uniqueOrderNo", uniqueOrderNo);
        //请求连接
        YopRequest request = new YopRequest("OPR:" + ParentMerchantNo, PRIVATEKEY);
        request.addParam("parentMerchantNo", ParentMerchantNo);
        request.addParam("merchantNo", MerchantNo);
        request.addParam("orderId", orderNo);
        request.addParam("uniqueOrderNo", uniqueOrderNo);
        request.addParam("hmac", HmacUtil.getYibaoOrderhamc(param));
        YopResponse response = YopRsaClient.post("/rest/v1.0/sys/trade/orderquery", request);
        JSONObject data = null;
        if ("FAILURE".equals(response.getState())) {
            if (response.getError() != null) {
                data.put("code", response.getError().getCode());
                data.put("message", response.getError().getMessage());
            }
        }
        if (response.getStringResult() != null) {
            Object object = JsonUtil.fromJson(response.getStringResult().toString(), Object.class);
            JSON json = (JSON) JSON.toJSON(object);
            data = JSONObject.parseObject(json.toJSONString());
        }
        return data;
    }


    /**
     * 调用易宝聚合API,主要提供扫码支付和公众号以及生活号支付
     * 返回JSAPI参数
     *
     * @param yibaoOrderToken     创建易宝订单返回的token
     * @param userwechat 微信用户
     * @param ip         请求IP
     * @return
     * @throws IOException
     */
    public static CashierdeskResult getPayUrl(String yibaoOrderToken, Userwechat userwechat, String ip) throws IOException {
        YopRequest request = new YopRequest("OPR:" + ParentMerchantNo, PRIVATEKEY);
        //订单 token
        request.addParam(Common.TOKEN, yibaoOrderToken);
        //支付工具
        request.addParam("payTool", "MINI_PROGRAM");
        //支付类型
        request.addParam("payType", "WECHAT");
        //用户标识
        request.addParam("userNo", userwechat.getUnionid());
        //用户标识类型
        request.addParam("userType", "USER_ID");
        //微信的appid
        request.addParam("appId", WechatUtil.mini_appid);
        //微信用户openid
        request.addParam("openId", userwechat.getOpenid());
        //用户真实的ip地址
        request.addParam("userIp", ip);
        //版本
        request.addParam("version", "1.0");
        YopResponse response = YopRsaClient.post("/rest/v1.0/nccashierapi/api/pay", request);
        CashierdeskResult cashierdeskResult = null;
        if ("FAILURE".equals(response.getState())) {
            cashierdeskResult = new CashierdeskResult();
            if (response.getError() != null) {
                cashierdeskResult.setCode(response.getError().getCode());
                cashierdeskResult.setMessage(response.getError().getMessage());
            }
        }
        if (response.getStringResult() != null) {
            Object object = JsonUtil.fromJson(response.getResult().toString(), Object.class);
            JSON json = (JSON) JSON.toJSON(object);
            cashierdeskResult = JSONObject.toJavaObject(json, CashierdeskResult.class);
        }
        return cashierdeskResult;
    }


    /**
     * 关闭易宝订单
     *
     * @param orderId       订单流水号(主订单号)
     * @param uniqueOrderNo 易宝订单流水号
     * @param description   关闭订单描述
     * @return
     * @throws IOException
     */
    public static JSONObject yibaoCloseOrder(String orderId, String uniqueOrderNo, String description) throws IOException {
        Map<String, String> param = new HashMap<>();
        param.put("parentMerchantNo", ParentMerchantNo);
        param.put("merchantNo", MerchantNo);
        //商户交易请求号
        param.put("orderId", orderId);
        //易宝内部生成唯一订单流水号
        param.put("uniqueOrderNo", uniqueOrderNo);
        //请求连接
        YopRequest request = new YopRequest("OPR:" + ParentMerchantNo, PRIVATEKEY);
        request.addParam("parentMerchantNo", ParentMerchantNo);
        request.addParam("merchantNo", MerchantNo);
        request.addParam("orderId", orderId);
        request.addParam("uniqueOrderNo", uniqueOrderNo);
        request.addParam("description", description);
        request.addParam("hmac", HmacUtil.getYibaoOrderhamc(param));
        YopResponse response = YopRsaClient.post("/rest/v1.0/sys/trade/orderclose", request);
        JSONObject data = null;
        if ("FAILURE".equals(response.getState())) {
            if (response.getError() != null) {
                data.put("code", response.getError().getCode());
                data.put("message", response.getError().getMessage());
            }
        }
        if (response.getStringResult() != null) {
            Object object = JsonUtil.fromJson(response.getStringResult().toString(), Object.class);
            JSON json = (JSON) JSON.toJSON(object);
            data = JSONObject.parseObject(json.toJSONString());
        }
        return data;
    }


    /**
     * 易宝退款
     *
     * @param yibaodivide
     * @param userorder
     * @param yibaopayment
     * @return
     * @throws IOException
     */
    public static Refundresult yibaoRefund(Yibaodivide yibaodivide, Userorder userorder, Yibaopayment yibaopayment) throws IOException {
        DecimalFormat amount = new DecimalFormat("0.00");
        Map<String, String> parms = new HashMap<>();
        parms.put("parentMerchantNo", ParentMerchantNo);
        parms.put("merchantNo", MerchantNo);
        //商户交易请求号
        parms.put("orderId", yibaodivide.getOrderId());
        //退款请求号
        String refundOrderNo = "4" + System.currentTimeMillis() + userorder.getId().toString();
        parms.put("refundRequestId", refundOrderNo);
        //易宝内部生成唯一订单流水号
        parms.put("uniqueOrderNo", yibaodivide.getUniqueOrderNo());
        //退款金额
        parms.put("refundAmount", amount.format(userorder.getPayableAmount()));
        YopRequest request = new YopRequest("OPR:" + ParentMerchantNo, PRIVATEKEY);
        request.addParam("parentMerchantNo", ParentMerchantNo);
        request.addParam("merchantNo", MerchantNo);
        //商户交易请求号
        request.addParam("orderId", yibaodivide.getOrderId());
        //退款请求号
        request.addParam("refundRequestId", refundOrderNo);
        //易宝内部生成唯一订单流水号
        request.addParam("uniqueOrderNo", yibaodivide.getUniqueOrderNo());
        //退款金额
        request.addParam("refundAmount", amount.format(userorder.getPayableAmount()));
        //
        String serviceCharge = amount.format(userorder.getPayableAmount() * 0.003);
        String realAmount = amount.format(userorder.getPayableAmount() - Double.valueOf(serviceCharge));
        String accountDivided = "";
        if (Double.valueOf(serviceCharge) > 0.00) {
            accountDivided = ",{\"ledgerNo\":\"10033201678\",\"amount\":" + serviceCharge + ",\"ledgerName\":\"春悦林（广东）大药房有限公司\"}";
        }
        request.addParam("accountDivided", "[{\"ledgerNo\":\"10033160799\",\"amount\":" + realAmount + ",\"ledgerName\":\"春悦林（广东）大药房有限公司\"}" + accountDivided + "]");
        //回调通知
        request.addParam("notifyUrl", RefundNotifyUrl);
        //hmac签名
        request.addParam("hmac", HmacUtil.getrefunddevidehamc(parms));
        YopResponse response = YopRsaClient.post("/rest/v1.0/sys/trade/refund", request);
        Refundresult refundresult = null;
        if ("FAILURE".equals(response.getState())) {
            refundresult = new Refundresult();
            refundresult.setCode(response.getError().getCode());
            refundresult.setMessage(response.getError().getMessage());
        }
        if (response.getStringResult() != null) {
            Object object = JsonUtil.fromJson(response.getStringResult().toString(), Object.class);
            JSON json = (JSON) JSON.toJSON(object);
            refundresult = JSONObject.toJavaObject(json, Refundresult.class);
        }
        return refundresult;
    }


    /**
     * 易宝退款查询
     *
     * @param orderId
     * @param uniqueRefundNo
     * @param refundRequestId
     * @return
     * @throws IOException
     */
    public static JSONObject yibaoGetRefund(String orderId, String uniqueRefundNo, String refundRequestId) throws IOException {
        DecimalFormat amount = new DecimalFormat("0.00");
        Map<String, String> parms = new HashMap<>();
        parms.put("parentMerchantNo", ParentMerchantNo);
        parms.put("merchantNo", MerchantNo);
        //交易请求号
        parms.put("orderId", orderId);
        //统一退款号
        parms.put("uniqueRefundNo", uniqueRefundNo);
        //退款请求号
        parms.put("refundRequestId", refundRequestId);
        YopRequest request = new YopRequest("OPR:" + ParentMerchantNo, PRIVATEKEY);
        request.addParam("parentMerchantNo", ParentMerchantNo);
        request.addParam("merchantNo", MerchantNo);
        //交易请求号
        request.addParam("orderId", orderId);
        //退款请求号
        request.addParam("refundRequestId", refundRequestId);
        //统一退款号
        request.addParam("uniqueRefundNo", uniqueRefundNo);
        //hmac签名
        request.addParam("hmac", HmacUtil.getrefundhamc(parms));
        YopResponse response = YopRsaClient.post("/rest/v1.0/sys/trade/refundquery", request);
        JSONObject data = null;
        if ("FAILURE".equals(response.getState())) {
            if (response.getError() != null) {
                data = new JSONObject();
                data.put("code", response.getError().getCode());
                data.put("message", response.getError().getMessage());
            }
        }
        if (response.getStringResult() != null) {
            Object object = JsonUtil.fromJson(response.getStringResult().toString(), Object.class);
            JSON json = (JSON) JSON.toJSON(object);
            data = JSONObject.parseObject(json.toJSONString());
        }
        return data;
    }


    /**
     * 易宝分账
     *
     * @param yibaopayment
     * @throws IOException
     */
    public static Divideresult yibaoDivide(Yibaopayment yibaopayment, Userorder userorder) throws IOException {
        DecimalFormat amount = new DecimalFormat("0.00");
        String divideRequestId = "3" + System.currentTimeMillis() + yibaopayment.getId().toString();
        Map<String, String> parms = new HashMap<>();
        YopRequest request = new YopRequest("OPR:" + ParentMerchantNo, PRIVATEKEY);
        parms.put("parentMerchantNo", ParentMerchantNo);
        parms.put("merchantNo", MerchantNo);
        parms.put("orderId", yibaopayment.getSerialNumber());
        parms.put("uniqueOrderNo", yibaopayment.getPaymentNo());
        parms.put("divideRequestId", divideRequestId);
        request.addParam("parentMerchantNo", ParentMerchantNo);
        request.addParam("merchantNo", MerchantNo);
        //商户交易请求号
        request.addParam("orderId", yibaopayment.getSerialNumber());
        //要分账订单的易宝流水号
        request.addParam("uniqueOrderNo", yibaopayment.getPaymentNo());
        //分账请求号
        request.addParam("divideRequestId", divideRequestId);
        //合同号
        request.addParam("contractNo", "10033160799");
        //分账明细
        Double serverCharge = Double.valueOf(amount.format(userorder.getPayableAmount() * 0.003));
        String realAmount = amount.format(userorder.getPayableAmount() - serverCharge);
        request.addParam("divideDetail", "[{\"ledgerNo\":\"10033160799\",\"amount\":" + realAmount + "}]");
//			request.addParam("divideDetail", "[{\\\"ledgerNo\\\":\"10033160799\",\\\"amount\\\":"+realAmount+"}]");
        //是否解冻收单商户剩余可用金额
        request.addParam("isUnfreezeResidualAmount", "FALSE");
        //签名
        request.addParam("hmac", HmacUtil.getdevidehamc(parms));
        YopResponse response = YopRsaClient.post("/rest/v1.0/sys/trade/divide", request);
        Divideresult divideresult = null;
        if ("FAILURE".equals(response.getState())) {
            divideresult = new Divideresult();
            divideresult.setCode(response.getError().getCode());
            divideresult.setMessage(response.getError().getMessage());
        }
        if (response.getStringResult() != null) {
            Object object = JsonUtil.fromJson(response.getStringResult().toString(), Object.class);
            JSON json = (JSON) JSON.toJSON(object);
            divideresult = JSONObject.toJavaObject(json, Divideresult.class);
        }
        return divideresult;
    }


    /**
     * 查询易宝分账
     *
     * @param orderId
     * @param uniqueOrderNo
     * @param divideRequestId
     * @return
     * @throws IOException
     */
    public static JSONObject getYibaoDivide(String orderId, String uniqueOrderNo, String divideRequestId) throws IOException {
        DecimalFormat amount = new DecimalFormat("0.00");
        Map<String, String> parms = new HashMap<>();
        YopRequest request = new YopRequest("OPR:" + ParentMerchantNo, PRIVATEKEY);
        parms.put("parentMerchantNo", ParentMerchantNo);
        parms.put("merchantNo", MerchantNo);
        parms.put("orderId", orderId);
        parms.put("uniqueOrderNo", uniqueOrderNo);
        parms.put("divideRequestId", divideRequestId);
        request.addParam("parentMerchantNo", ParentMerchantNo);
        request.addParam("merchantNo", MerchantNo);
        //商户交易请求号
        request.addParam("orderId", orderId);
        //要分账订单的易宝流水号
        request.addParam("uniqueOrderNo", uniqueOrderNo);
        //分账请求号
        request.addParam("divideRequestId", divideRequestId);
        //合同号
//			request.addParam("contractNo", "10033160799");
        //签名
        request.addParam("hmac", HmacUtil.getdevidehamc(parms));
        YopResponse response = YopRsaClient.post("/rest/v1.0/sys/trade/dividequery", request);
        JSONObject data = null;
        if ("FAILURE".equals(response.getState())) {
            if (response.getError() != null)
                data = new JSONObject();
            data.put("code", response.getError().getCode());
            data.put("message", response.getError().getMessage());
        }
        if (response.getStringResult() != null) {
            Object object = JsonUtil.fromJson(response.getStringResult().toString(), Object.class);
            JSON json = (JSON) JSON.toJSON(object);
            data = JSONObject.parseObject(json.toJSONString());
        }
        return data;
    }


    /**
     * 回调方法
     *
     * @param response
     * @return
     */
    public static String callBack(String response) {
        DigitalEnvelopeDTO dto = new DigitalEnvelopeDTO();
        dto.setCipherText(response);
        try {
            //设置商户私钥
            PrivateKey privateKey = getPrivateKey();
            //设置易宝公钥
            PublicKey publicKey = getPubKey();
            //解密验签
            dto = DigitalEnvelopeUtils.decrypt(dto, privateKey, publicKey);
            //打印回调数据
            return dto.getPlainText();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 实例化公钥
     *
     * @return
     */
    private static PublicKey getPubKey() {
        PublicKey publicKey = null;
        // RSA对称加密算法
        try {
            X509EncodedKeySpec bobPubKeySpec = new X509EncodedKeySpec(new BASE64Decoder().decodeBuffer(PUBLICKEY));
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            publicKey = keyFactory.generatePublic(bobPubKeySpec);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        }
        return publicKey;
    }

    /**
     * 实例化密钥
     *
     * @return
     */
    private static PrivateKey getPrivateKey() {
        PrivateKey privateKey = null;
        try {
            PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(new BASE64Decoder().decodeBuffer(PRIVATEKEY));
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            privateKey = keyFactory.generatePrivate(priPKCS8);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        }
        return privateKey;
    }

    /**
     * 易宝分账退回工具
     *
     * @throws IOException
     */
    public static JSONObject yibaoDividereturn(String orderId, String uniqueOrderNo, String divideRequestId, String divideDetailNo, Double price, String reason) throws IOException {
        DecimalFormat amount = new DecimalFormat("0.00");
        String divideBackRequestId = "6" + System.currentTimeMillis() + SmsUtil.getRandom(3).toString();
        Map<String, String> parms = new HashMap<>();
        YopRequest request = new YopRequest("OPR:" + ParentMerchantNo, PRIVATEKEY);
        parms.put("parentMerchantNo", ParentMerchantNo);
        parms.put("merchantNo", MerchantNo);
        parms.put("orderId", orderId);
        parms.put("uniqueOrderNo", uniqueOrderNo);
        parms.put("divideRequestId", divideRequestId);
        request.addParam("parentMerchantNo", ParentMerchantNo);
        request.addParam("merchantNo", MerchantNo);
        //商户交易请求号
        request.addParam("orderId", orderId);
        //要分账订单的易宝流水号
        request.addParam("uniqueOrderNo", uniqueOrderNo);
        //分账请求号
        request.addParam("divideRequestId", divideRequestId);
        //商户分账退回请求号
        request.addParam("divideBackRequestId", divideBackRequestId);
        //分账明细
        String money = amount.format(price);
        DivideBackDetail divideBackDetail = new DivideBackDetail(money, reason, divideDetailNo);
        String jsonString = "[" + JsonUtil.toJson(divideBackDetail) + "]";
        request.addParam("divideBackDetail", jsonString);
        //签名
        request.addParam("hmac", HmacUtil.getdevidehamc(parms));
        YopResponse response = YopRsaClient.post("/rest/v1.0/sys/trade/divideback", request);
        JSONObject data = null;
        if ("FAILURE".equals(response.getState())) {
            if (response.getError() != null)
                data = new JSONObject();
            data.put("code", response.getError().getCode());
            data.put("message", response.getError().getMessage());
        }
        if (response.getStringResult() != null) {
            Object object = JsonUtil.fromJson(response.getStringResult().toString(), Object.class);
            JSON json = (JSON) JSON.toJSON(object);
            data = JSONObject.parseObject(json.toJSONString());
        }
        return data;
    }

    /**
     * 资金全额确认
     *
     * @throws IOException
     */
    public static JSONObject yibaoFullsettle(String orderId, String uniqueOrderNo) throws IOException {
        Map<String, String> parms = new HashMap<>();
        parms.put("parentMerchantNo", ParentMerchantNo);
        parms.put("merchantNo", MerchantNo);
        parms.put("orderId", orderId);
        parms.put("uniqueOrderNo", uniqueOrderNo);
        YopRequest request = new YopRequest("OPR:" + ParentMerchantNo, PRIVATEKEY);
        request.addParam("parentMerchantNo", ParentMerchantNo);
        request.addParam("merchantNo", MerchantNo);
        //商户交易请求号
        request.addParam("orderId", orderId);
        //要分账订单的易宝流水号
        request.addParam("uniqueOrderNo", uniqueOrderNo);
        //签名
        request.addParam("hmac", HmacUtil.getfullsettlehamc(parms));
        YopResponse response = YopRsaClient.post("/rest/v1.0/sys/trade/fullsettle", request);
        JSONObject data = null;
        if ("FAILURE".equals(response.getState())) {
            if (response.getError() != null)
                data = new JSONObject();
            data.put("code", response.getError().getCode());
            data.put("message", response.getError().getMessage());
        }
        if (response.getStringResult() != null) {
            Object object = JsonUtil.fromJson(response.getStringResult().toString(), Object.class);
            JSON json = (JSON) JSON.toJSON(object);
            data = JSONObject.parseObject(json.toJSONString());
        }
        return data;

    }

    /**
     * 测试易宝退款
     *
     * @throws IOException
     */
    public static Refundresult testyibaoRefund(String orderId, String uniqueOrderNo, String refundRequestId, Double price, Double realAmount, Double serviceCharge) throws IOException {
        DecimalFormat amount = new DecimalFormat("0.00");
        Map<String, String> parms = new HashMap<>();
        parms.put("parentMerchantNo", ParentMerchantNo);
        parms.put("merchantNo", MerchantNo);
        //商户交易请求号
        parms.put("orderId", orderId);
        //退款请求号
        String refundOrderNo = "4" + System.currentTimeMillis() + SmsUtil.getRandom(4).toString();
        if (refundRequestId != null) {
            parms.put("refundRequestId", refundRequestId);
        } else {
            parms.put("refundRequestId", refundOrderNo);
        }
        //易宝内部生成唯一订单流水号
        parms.put("uniqueOrderNo", uniqueOrderNo);
        //退款金额
        parms.put("refundAmount", amount.format(price));
        YopRequest request = new YopRequest("OPR:" + ParentMerchantNo, PRIVATEKEY);
        request.addParam("parentMerchantNo", ParentMerchantNo);
        request.addParam("merchantNo", MerchantNo);
        //商户交易请求号
        request.addParam("orderId", orderId);
        //退款请求号
        if (refundRequestId != null) {
            request.addParam("refundRequestId", refundRequestId);
        } else {
            request.addParam("refundRequestId", refundOrderNo);
        }
        //易宝内部生成唯一订单流水号
        request.addParam("uniqueOrderNo", uniqueOrderNo);
        //退款金额
        request.addParam("refundAmount", amount.format(price));
        //
        String realAmountStr = amount.format(realAmount);
        String serviceChargeStr = amount.format(serviceCharge);
        String accountDivided = "";
        if (Double.valueOf(serviceCharge) > 0.00) {
            accountDivided = ",{\"ledgerNo\":\"10033201678\",\"amount\":" + serviceChargeStr + ",\"ledgerName\":\"春悦林（广东）大药房有限公司\"}";
        }
        request.addParam("accountDivided", "[{\"ledgerNo\":\"10033160799\",\"amount\":" + realAmountStr + ",\"ledgerName\":\"春悦林（广东）大药房有限公司\"}" + accountDivided + "]");
        //回调通知
        request.addParam("notifyUrl", RefundNotifyUrl);
        //hmac签名
        request.addParam("hmac", HmacUtil.getrefunddevidehamc(parms));
        YopResponse response = YopRsaClient.post("/rest/v1.0/sys/trade/refund", request);
        Refundresult refundresult = null;
        if ("FAILURE".equals(response.getState())) {
            refundresult = new Refundresult();
            refundresult.setCode(response.getError().getCode());
            refundresult.setMessage(response.getError().getMessage());
        }
        if (response.getStringResult() != null) {
            Object object = JsonUtil.fromJson(response.getStringResult().toString(), Object.class);
            JSON json = (JSON) JSON.toJSON(object);
            refundresult = JSONObject.toJavaObject(json, Refundresult.class);
        }
        return refundresult;
    }


    /**
     * 测试易宝分账
     *
     * @throws IOException
     */
    public static Divideresult testyibaoDivide(String orderId, String uniqueOrderNo, Double price) throws IOException {
        DecimalFormat amount = new DecimalFormat("0.00");
        String divideRequestId = "3" + System.currentTimeMillis() + SmsUtil.getRandom(3).toString();
        Map<String, String> parms = new HashMap<>();
        YopRequest request = new YopRequest("OPR:" + ParentMerchantNo, PRIVATEKEY);
        parms.put("parentMerchantNo", ParentMerchantNo);
        parms.put("merchantNo", MerchantNo);
        parms.put("orderId", orderId);
        parms.put("uniqueOrderNo", uniqueOrderNo);
        parms.put("divideRequestId", divideRequestId);
        request.addParam("parentMerchantNo", ParentMerchantNo);
        request.addParam("merchantNo", MerchantNo);
        //商户交易请求号
        request.addParam("orderId", orderId);
        //要分账订单的易宝流水号
        request.addParam("uniqueOrderNo", uniqueOrderNo);
        //分账请求号
        request.addParam("divideRequestId", divideRequestId);
        //合同号
        request.addParam("contractNo", "10033160799");
        //分账明细
        String money = amount.format(price);
        request.addParam("divideDetail", "[{\"ledgerNo\":\"10033160799\",\"amount\":" + money + "}]");
        //是否解冻收单商户剩余可用金额
        request.addParam("isUnfreezeResidualAmount", "FALSE");
        //签名
        request.addParam("hmac", HmacUtil.getdevidehamc(parms));
        YopResponse response = YopRsaClient.post("/rest/v1.0/sys/trade/divide", request);
        Divideresult divideresult = null;
        if ("FAILURE".equals(response.getState())) {
            divideresult = new Divideresult();
            divideresult.setCode(response.getError().getCode());
            divideresult.setMessage(response.getError().getMessage());
        }
        if (response.getStringResult() != null) {
            Object object = JsonUtil.fromJson(response.getStringResult().toString(), Object.class);
            JSON json = (JSON) JSON.toJSON(object);
            divideresult = JSONObject.toJavaObject(json, Divideresult.class);
        }
        return divideresult;
    }


    public static void main(String[] args) throws IOException {
//			Divideresult divideresult=testyibaoDivide("00001631584344906167", "1001202003160000001472457938", 0.85);
//			System.out.println(divideresult.toString());
//			Refundresult refundresult=testyibaoRefund("00626761581948547046", "1001202002170000001444024274",null,19.8,19.74,0.06);
//			System.out.println(refundresult.toString());
//			JSONObject data=yibaoFullsettle("00268921579232073993", "1001202001170000001415681097");
//			System.out.println(data.toJSONString());
//			JSONObject data=getYibaoorder("0158139969384927703", "1001202002110000001438828115");
//			System.out.println(data.toJSONString());
//			JSONObject data=yibaoGetRefund("00000151583924300058", "1001202003110000001466703683", "4158392484280332693");
//			System.out.println(data.toJSONString());
//			JSONObject data=getYibaoDivide("00001631584344906167", "1001202003160000001472457938", "31584345078917073");
//			System.out.println(data.toJSONString());
//			JSONObject data=yibaoDividereturn("00001631584344906167", "1001202003160000001472457938", "31584345078917073", "",0.85,"操作失误");
//			System.out.println(data.toJSONString());
//			JSONObject data=yibaoCloseOrder("00277031581399372279", "1001202002110000001438822753", "订单取消支付");
//			System.out.println(data.toJSONString());
        String responseString = "gE-S4PQM8V9N2RmOKAV6lGWfLQxukxoGWvkFxL0xRIokgSDxT2dOag4RhVARTaJim1_pdANB736kNswznWT3rg2l_T0nLa-rOiPKKtOa0UIWAkLJT3Co0d-EyUEjJg2moq3FzCTsZfwePZvXL15Qi0Xe5mKbqF3J3-j11gkFaeZwfx_TwHK1sxJPoFRgvx98e4xtY6UvPCB5aResaKvQpTeQhuqytTZMl_5Qy_Zkxo68UNmix8A64D4btgnNfGuH4v_yYp-D1XTZ4K-3FL50ibua0_19-Y3KOtIn-RKyNBgHkAUSxTbJIqz6ELDZtMCT04jWwDiiq1dJ6cA9CTU-3A$WxQgMTUrHuAcDkesGce-JAwAU3-ltfUT5RsyKjQI4bhuR2x9KkeRGp9FG9syIDEhpSu2kK1_njVoPhpfwmdBDLYK25-qNqjtwgbDP-0S78kQVXxxmi4tS17qwAan8sHUpLgg3-nVAX3FC_q2UvBRb2SFgcPHy24Yrjbh4T9NcTlWIV_Vvqn3nJZt9eUZhWLcESEngzCTKnTBoxLDEHAVYRNdz8gaq7W1-vxTD4r-cAMAvlHGKIhQUUVUBaZC19e1Q94JPBT95A7tJhFWXtDbUaO6RNXfrVUMZRXmFWMnAc86rAhxXofUBSCxbR6bt-Xus9OQ0peKCZxwnzC48Kt6v0xWynHGsxNZDS3aTHsoSvcz9W4AEE8H_Sq7NnUxlwiKmmjRmDt4I6B0s5IEm47ZjulcSnTo4VD6Pfu4-N9NI_D6h1a-ZAJfLU2Lr0ObhM3bT-Z8eaU56l8gNIO5qZcJzR7x1HXjokARKEbHJLDmtvwNDqPI715bcRxH2u2W0HcG5XpEbIwegh7amFkPx3_IW3z_1ufKTWsSi1kHa-U2WhHFKiSlJVX4TLhgtfl1r4N8yfGKRwOek3AVkUsq0mu84zoTXvymiF5Dbcp6dwyscWd38858PTW0KRXKBMXZQ-VQ5-8QkV1iJ_AUPsFiWBrWLIG7EkUwvXiKKkpqTlcxmPttT35roSaPLhnFHxWYSzBQJZnDnnaLIw5M_M0l0L7ko662Femm9E6u1N7YqlGRHGgEd0rV3IVtmSQ2BIgfSkDrFKjwa3uFXyUwzsJFnpC8sLXU29089Hm2e2-53z7Vq4mHbALHoWT_3sR7BYjL-6XaLeinWha4yzdbWEVVvN1yO0jZQnfUVOEfWyAxGocDJqBo9YxRWF7v2oI2UtupWpkGlML_mRbtlPBuDfpqwPJ2A1k3udl-i1mezQ9ZlLe-tEcc80rC7msIXo1J3b5yzgeoELvcnm6KNuMZXGW1YTNykA$AES$SHA256";
        String result = callBack(responseString);
        System.out.println(result);
    }
}
